# -*- coding: utf-8 -*-
# @Time    : 2024/5/22 11:27
# @Author  : Alvin
# @File    : auth.py
from flask import Flask, request, jsonify,Blueprint
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity,create_refresh_token,set_access_cookies,set_refresh_cookies,unset_jwt_cookies
from ..services.user_service import check_user_password, create_user

auth_bp = Blueprint('auth', __name__)

# 路由用于用户登录并生成 Token
@auth_bp.route('/login', methods=['POST'])
def login():
    username = request.json.get('username')
    password = request.json.get('password')

    # 验证用户身份
    result, user = check_user_password(username, password)
    if result == 'success':
        # 如果验证成功，创建并返回一个 Token
        access_token = create_access_token(identity=username)
        refresh_token = create_refresh_token(identity=username)
        resp = jsonify(status_code=200,
                       data={"access_token": access_token, "refresh_token":refresh_token, "user": user}
                       )
        set_access_cookies(resp, access_token)
        set_refresh_cookies(resp, refresh_token)
        return resp, 200

    elif result == 'password_error':
        # 如果密码错误，返回错误信息
            return jsonify(message='Invalid password'), 403
    else:
        # 如果账号不存在，返回错误信息
        return jsonify(message='User not found'), 404

@auth_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)
    resp = jsonify({'refresh': True, 'access_token': access_token})
    set_access_cookies(resp, access_token)
    return resp, 200
# 新增注册路由
@auth_bp.route('/register', methods=['POST'])
def register():
    username = request.json.get('username')
    password = request.json.get('password')
    email = request.json.get('email')  # 可选
    nickname = request.json.get('nickname')  # 可选

    # 验证用户输入
    if not username or not password:
        return jsonify(status_code=400, message='Username and password are required'), 400

    # 创建新用户
    result, message = create_user(username, password, email, nickname)
    if result:
        return jsonify(status_code=200, message='User registered successfully'), 200
    else:
        return jsonify(status_code=400, message=message), 400

@auth_bp.route('/logout', methods=['POST'])
def logout():
    resp = jsonify({'logout': True})
    unset_jwt_cookies(resp)
    return resp, 200
# 受保护的路由，需要 Token 鉴权
@auth_bp.route('/protected', methods=['GET'])
@jwt_required()
def protected_route():
    current_user = get_jwt_identity()
    return jsonify(message=f'Hello, {current_user}! This route is protected by JWT.')

